package org.dalmatian.common.idempotent.interceptor;


import cn.dev33.satoken.SaManager;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import org.dalmatian.common.core.constants.GlobalConstants;
import org.dalmatian.common.core.domain.R;
import org.dalmatian.common.core.exception.ServiceException;
import org.dalmatian.common.core.utils.JsonUtils;
import org.dalmatian.common.core.utils.MessageUtils;
import org.dalmatian.common.core.utils.StringUtils;
import org.dalmatian.common.idempotent.annotation.RepeatSubmit;
import org.dalmatian.common.redis.utils.RedisUtils;
import java.time.Duration;
import java.util.Collection;
import java.util.Map;
import java.util.StringJoiner;
import org.noear.solon.core.aspect.Interceptor;
import org.noear.solon.core.aspect.Invocation;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.UploadedFile;


/**
 * 防止重复提交(参考美团GTIS防重系统)
 *
 * @author Lion Li
 */

public class RepeatSubmitInterceptor implements Interceptor {

    private static final ThreadLocal<String> KEY_CACHE = new ThreadLocal<>();

    @Override
    public Object doIntercept(Invocation inv) throws Throwable {
        RepeatSubmit anno = inv.getMethodAnnotation(RepeatSubmit.class);
        if (anno == null) {
            anno = inv.getTargetAnnotation(RepeatSubmit.class);
        }
        if (anno == null) {
            return inv.invoke();
        } else {
            doBefore(inv, anno);
            Object result;
            try {
                result = inv.invoke();
                doAfterReturning(result);
                return result;
            } catch (Throwable e) {
                doAfterThrowing();
                throw  e;
            }
        }
    }


    /**
     * 执行开始前 inv
     *
     * @param inv
     * @param repeatSubmit
     * @throws Throwable
     */
    public void doBefore(Invocation inv, RepeatSubmit repeatSubmit) throws Throwable {
        // 如果注解不为0 则使用注解数值
        long interval = repeatSubmit.timeUnit().toMillis(repeatSubmit.interval());
        if (interval < 1000) {
            throw new ServiceException("重复提交间隔时间不能小于'1'秒");
        }

        String nowParams = argsArrayToString(inv.args());
        // 请求地址（作为存放cache的key值）
        Context context = Context.current();
        String url = context.path();
        // 唯一值（没有消息头则使用请求地址）
        String submitKey = StringUtils.trimToEmpty(
            context.header(SaManager.getConfig().getTokenName()));
        submitKey = SecureUtil.md5(submitKey + ":" + nowParams);
        // 唯一标识（指定key + url + 消息头）
        String cacheRepeatKey = GlobalConstants.REPEAT_SUBMIT_KEY + url + submitKey;
        if (RedisUtils.setObjectIfAbsent(cacheRepeatKey, "", Duration.ofMillis(interval))) {
            KEY_CACHE.set(cacheRepeatKey);
        } else {
            String message = repeatSubmit.message();
            if (StringUtils.startsWith(message, "{") && StringUtils.endsWith(message, "}")) {
                message = MessageUtils.message(
                    StringUtils.substring(message, 1, message.length() - 1));
            }
            throw new ServiceException(message);
        }
    }

    /**
     * 处理完请求后执行
     *
     * @param
     */
    public void doAfterReturning(Object jsonResult) {
        if (jsonResult instanceof R<?> r) {
            try {
                // 成功则不删除redis数据 保证在有效时间内无法重复提交
                if (r.getCode() == R.SUCCESS) {
                    return;
                }
                RedisUtils.deleteObject(KEY_CACHE.get());
            } finally {
                KEY_CACHE.remove();
            }
        }
    }

    /**
     * 拦截异常操作
     */
    public void doAfterThrowing() {
        RedisUtils.deleteObject(KEY_CACHE.get());
        KEY_CACHE.remove();
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringJoiner params = new StringJoiner(" ");
        if (ArrayUtil.isEmpty(paramsArray)) {
            return params.toString();
        }
        for (Object o : paramsArray) {
            if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) {
                params.add(JsonUtils.toJsonString(o));
            }
        }
        return params.toString();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return UploadedFile.class.isAssignableFrom(clazz.getComponentType());
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof UploadedFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.values()) {
                return value instanceof UploadedFile;
            }
        }
        return o instanceof UploadedFile;

    }


}
